<template>
	<view>
		<map :id="mapId" :longitude="longitude" :latitude="latitude" :scale="scale" :markers="markers" :polyline="polyline"
		 :enable-satellite="satellite" show-location style="width: 100%; height: 100vh;"
		 @markertap="tapMarker"></map>
	</view>
</template>

<script>
	export default {
		components: {

		},
		props: {
			mapId: {
				type: String,
				default: 'mapId_contrail'
			},
			points: {
				type: Array,
				default () {
					return []
				}
			},
			scale: {
				type: Number,
				default: 14
			},
			latitude: {
				type: Number,
				default: 39.806466
			},
			longitude: {
				type: Number,
				default: 98.226473
			},
			//是否开启卫星图
			satellite: {
				type: Boolean,
				default: true
			},
		},
		data() {
			return {
				i: 0, // 用于循环
				markers: [], // 标记点集合
				polyline: [], // 坐标点集合
				mapCtx : {},
			}
		},
		mounted:function(){
			let that = this;
			that.mapCtx = uni.createMapContext(that.mapId,this); // 创建 map 上下文 MapContext 对象
			
		},
		watch: {
			points(e) {
				let that = this;
				if(that.points.length>0){
					that.setDateByPoints(that.points) ;
				}
				
			},
		},
		created: function() {
			let that = this;
			if(that.points.length>0){
				that.setDateByPoints(that.points) ;
			}
		},
		methods: {
			tapMarker(e){
				this.$emit('markertap', e);
			},
			setDateByPoints(points) {
				let that = this;
				
				// 标记点集合
				
				let markers = points;
				
				markers.map((value, index) => {
					markers[index].id = index + 1;
				});
				
				

				that.polyline = [{
					points: points,
					color: "#FF0000DD",
					width: 2
				}];
				that.markers = markers;


				this.translateMarker(markers);
			},
			// 平移marker，带动画
			translateMarker: function(markers) {
				let that = this;
				let markerId = markers[that.i].id ;
				
				let destination = {
					longitude: markers[that.i + 1].longitude,
					latitude: markers[that.i + 1].latitude
				};
				let getDistance = that.getDistance(markers[that.i].latitude, markers[that.i].longitude, markers[that.i + 1].latitude,
					markers[that.i + 1].longitude);
				let duration = getDistance * 2; // 根据距离计算平移的速度，看起来保持匀速
				
				this.mapCtx.translateMarker({
					markerId: markerId,
					destination: destination,
					autoRotate: true,
					rotate: 30,
					duration: duration,
					success(res) {
						that.i = that.i + 1;
						
						// 小于长度减1才执行
						if (that.i < markers.length - 1) {
							that.translateMarker(markers);
						}
					},
					fail(err) {
						console.log('fail', err)
					}
				})
			},
			// 计算两坐标点之间的距离
			getDistance: function(lat1, lng1, lat2, lng2) {
				let rad1 = lat1 * Math.PI / 180.0;
				let rad2 = lat2 * Math.PI / 180.0;
				let a = rad1 - rad2;
				let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
				let r = 6378137;
				return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math
					.sin(b / 2), 2)))).toFixed(0)

			},

		},
	}
</script>

<style>
</style>


